package tcp;

import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;

public class tregisters_6 {
	public static String ipAdress;
	public static int ipPort;
	public static int slaveId;
	public static int start;
	public static short[] values;
	public tregisters_6(String ipAdress1, int ipPort1, int slaveId1, int start1, short[] values1)
	{
		ipAdress = ipAdress1; 
		ipPort = ipPort1;
		 slaveId = slaveId1;
		 start = start1;
		 values  = values1;
	};
	public static int remain1(){
		int result;
		IpParameters ipParameters = new IpParameters();
        ipParameters.setHost(ipAdress);
        ipParameters.setPort(ipPort);
		ModbusFactory modbusFactory = new ModbusFactory();

		ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, false);
        try {
			master.init();
		} catch (ModbusInitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        result = writeRegistersTest(master, slaveId, start, values);
        master.destroy();
        return result;
	};
	
	 public static int writeRegistersTest(ModbusMaster master, int slaveId3, int start3, short[] values3) {
	     int result1 = 0;   
		 try {
	            WriteRegistersRequest request = new WriteRegistersRequest(slaveId3, start3, values3);
	            WriteRegistersResponse response = (WriteRegistersResponse) master.send(request);

	            if (response.isException())
	               {
	            	System.out.println("Exception response: message=" + response.getExceptionMessage());
	               result1 = 0;
	               }
	            else
	                {
	            	System.out.println("Success");
	                result1 = 1;
	                }
	        }
	        catch (ModbusTransportException e) {
	            e.printStackTrace();
	        }
		 return result1;
	    }

}
